#include "Live2D.h"
#include "HtmlBuilder.h"
#include <QTimer>

Live2D::Live2D(QWidget *parent) : QWebEngineView(parent)
{
    this->setWindowFlags(Qt::FramelessWindowHint
                     |Qt::X11BypassWindowManagerHint
                     |Qt::Tool);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setAttribute(Qt::WA_TransparentForMouseEvents, true);
    this->setContextMenuPolicy(Qt::NoContextMenu);
    this->page()->setBackgroundColor(Qt::transparent);
    AddSystemTrayMenu();
    ChangeModel(Config::Instance()->GetDefaultModel());
}

void Live2D::AddSystemTrayMenu()
{
    // 托盘图标右键菜单
    actionMap = QMap<QString, QAction*>();
    auto addAction = [&](const QString& model) {
        auto* action = new QAction(model, this);
        action->setCheckable(true);
        connect(action, &QAction::triggered, this, [this, model](){
            this->ChangeModel(model);
        });
        actionMap.insert(model, action);
    };
    for (const auto& i : Config::Instance()->GetModelList())
    {
        addAction(i);
    }

    auto* modelMenu = new QMenu("切换模型", this);
    for (const auto& i : actionMap)
    {
        modelMenu->addAction(i);
    }
    auto* modelGroup = new QActionGroup(modelMenu);
    modelGroup->setExclusive(true);
    for (const auto& i : actionMap)
    {
        modelGroup->addAction(i);
    }

    auto* quitAction = new QAction("退出", this);
    connect(quitAction, &QAction::triggered, this, &QCoreApplication::quit);

    auto* trayIconMenu = new QMenu(this);
    trayIconMenu->addMenu(modelMenu);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    auto* trayIcon = new QSystemTrayIcon(this);
    trayIcon->setToolTip("Live2D");
    trayIcon->setIcon(QIcon(":/icon.svg"));
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setVisible(true);
    trayIcon->show();
}

void Live2D::SetWindowPos()
{
    auto size = HtmlBuilder::Instance()->GetWindowSize(currentModel);
    auto offset = Config::Instance()->GetWindowCreateOffset();
    this->resize(size.width(), size.height());
    this->move(QApplication::desktop()->width() - size.width() + offset.x(),
           QApplication::desktop()->height() - size.height() + offset.y());
}

void Live2D::ChangeModel(const QString &modelName)
{
    this->setVisible(false);
    currentModel = modelName;
    this->SetWindowPos();
    this->setHtml(HtmlBuilder::Instance()->GetHtml(currentModel));
    this->actionMap[currentModel]->setChecked(true);
    QTimer::singleShot(30, this, [this](){
        this->setVisible(true);
    });
}
